package com.tywj.lib.core.common.extension

import io.reactivex.*
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers

/**
 * <pre>
 *     author : June Yang
 *     time   : 2020/5/7
 *     desc   : RxJava扩展
 *     version: 1.0.0
 * </pre>
 */

/**
 * 安全解除订阅
 */
fun Disposable.safeDisposable() {
    if (!this.isDisposed) {
        this.dispose()
    }
}

/**
 * Observable 应用线程控制
 * @param subscribeScheduler 订阅时的线程，默认是 IO 线程
 * @param observeScheduler 观察时的线程，默认是主线程
 */
fun <T> Observable<T>.applyScheduler(
        subscribeScheduler: Scheduler = Schedulers.io(),
        observeScheduler: Scheduler = AndroidSchedulers.mainThread()
): Observable<T> {
    return this.subscribeOn(subscribeScheduler)
            .observeOn(observeScheduler)
            .unsubscribeOn(subscribeScheduler)
}

/**
 * Flowable 应用线程控制
 * @param subscribeScheduler 订阅时的线程，默认是 IO 线程
 * @param observeScheduler 观察时的线程，默认是主线程
 */
fun <T> Flowable<T>.applyScheduler(
        subscribeScheduler: Scheduler = Schedulers.io(),
        observeScheduler: Scheduler = AndroidSchedulers.mainThread()
): Flowable<T> {
    return this.subscribeOn(subscribeScheduler)
            .observeOn(observeScheduler)
            .unsubscribeOn(subscribeScheduler)
}

/**
 * Single 应用线程控制
 * @param subscribeScheduler 订阅时的线程，默认是 IO 线程
 * @param observeScheduler 观察时的线程，默认是主线程
 */
fun <T> Single<T>.applyScheduler(
        subscribeScheduler: Scheduler = Schedulers.io(),
        observeScheduler: Scheduler = AndroidSchedulers.mainThread()
): Single<T> {
    return this.subscribeOn(subscribeScheduler)
            .observeOn(observeScheduler)
            .unsubscribeOn(subscribeScheduler)
}

/**
 * Maybe 应用线程控制
 * @param subscribeScheduler 订阅时的线程，默认是 IO 线程
 * @param observeScheduler 观察时的线程，默认是主线程
 */
fun <T> Maybe<T>.applyScheduler(
        subscribeScheduler: Scheduler = Schedulers.io(),
        observeScheduler: Scheduler = AndroidSchedulers.mainThread()
): Maybe<T> {
    return this.subscribeOn(subscribeScheduler)
            .observeOn(observeScheduler)
            .unsubscribeOn(subscribeScheduler)
}

/**
 * Completable 应用线程控制
 * @param subscribeScheduler 订阅时的线程，默认是 IO 线程
 * @param observeScheduler 观察时的线程，默认是主线程
 */
fun Completable.applyScheduler(
        subscribeScheduler: Scheduler = Schedulers.io(),
        observeScheduler: Scheduler = AndroidSchedulers.mainThread()
): Completable {
    return this.subscribeOn(subscribeScheduler)
            .observeOn(observeScheduler)
            .unsubscribeOn(subscribeScheduler)
}